package com.leyou.cart.service;

import com.leyou.cart.pojo.Cart;
import com.leyou.cart.utils.UserHolder;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "cart:uid:";

    public void addItemToCart(Cart cart) {
        // 获取用户id
        Long id = UserHolder.getUser().getId();
        String key = KEY_PREFIX + id;
        // 创建hash数据操作对象
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        // 判断是否存在当前商品
        String skuId = cart.getSkuId().toString();
        Boolean exists = hashOps.hasKey(skuId);
        if(exists){
            // 如果存在，获取已经存在的商品
            String json = hashOps.get(skuId);
            Cart cacheCart = JsonUtils.toBean(json, Cart.class);
            // 修改数量
            cart.setNum(cacheCart.getNum() + cart.getNum());
        }
        // 写入redis
        hashOps.put(skuId, JsonUtils.toString(cart));
    }

    public List<Cart> queryCartList() {
        // 获取用户id
        Long id = UserHolder.getUser().getId();
        String key = KEY_PREFIX + id;
        // 判断key是否存在
        Boolean exits = redisTemplate.hasKey(key);
        if(exits ==null || !exits){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        // 创建hash数据操作对象
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        // 获取用户的所有购物车
        List<String> values = hashOps.values();
        if (CollectionUtils.isEmpty(values)) {
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        // 反序列化数据
        return values.stream().map(json -> JsonUtils.toBean(json, Cart.class)).collect(Collectors.toList());
    }
}
